package com.sfdcj.se.meta;

import java.io.IOException;
import java.util.Hashtable;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sfdcj.se.SfdcException;

import com.sfdcj.se.meta.proc.Processor;
import com.sfdcj.se.meta.proc.SObjectDirectCreateProcessor;

public class MainServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	static private Hashtable<String, Processor> procs;

	static private String ERROR_PAGE = ".meta/error.jsp";

	static {
		procs = new Hashtable<String, Processor>();
		procs.put("meta", new SObjectDirectCreateProcessor());
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		Outcome outcome = null;
		request.setCharacterEncoding("UTF-8");

		try {
			String mode = "meta";
			Processor proc = procs.get(mode);
			outcome = proc.execute(request, response);
			request.setAttribute("bean", outcome.obj);
			forward(request, response, outcome.returnJsp);

		} catch (SfdcException e) {
			request.setAttribute("msg", e.toString());
			forward(request, response, ERROR_PAGE);
		}
	}

	public void forward(HttpServletRequest request,
			HttpServletResponse response, String jsp) throws ServletException,
			IOException {
		RequestDispatcher rd = request.getRequestDispatcher(jsp);
		rd.forward(request, response);
	}
}
